package com.sgb.merchant.view.activity;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.util.Pair;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.google.android.material.tabs.TabLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.merchant.IndustryCategoryEntity;
import com.sgb.link.entity.merchant.IndustryListEntity;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.view.widget.CustomXTabLayout;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivityIndustryListBinding;
import com.sgb.merchant.view.adapter.IndustryListAdapter;
import com.sgb.merchant.viewmodel.IndustryViewModel;
import com.sgb.merchant.widget.SelectTypeWindow;
import com.sgb.net.entity.ListResponse;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

/**
 * @author: 王彬臣
 * @date: 2021/10/13
 * @Description: 产业园区列表
 */
@Route(path = PathMerchant.IndustryListActivity)
public class IndustryListActivity extends BaseActivity<IndustryViewModel, MerchantActivityIndustryListBinding> {
    Map<String, Object> mMap;
    private boolean mIsLoadMore;
    private boolean mIsHasSearch = false;
    private boolean isChange1, isChange2, isChange3;
    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> cityData;
    List<IndustryListEntity> mList = new ArrayList<>();
    List<IndustryCategoryEntity> mLeveList = new ArrayList<>();
    List<IndustryCategoryEntity> mGroupList = new ArrayList<>();

    private int STATE_PUBLISH_TIME = 0;
    private final static int STATE_PUBLISH_TIME_UP = 1;
    private final static int STATE_PUBLISH_TIME_DOWN = 2;
    private final static int STATE_PUBLISH_TIME_NONE = 0;

    IndustryListAdapter mAdapter;
    private String no;

    SelectTypeWindow mLevePop, mGroupPop;
    private String leveTypeName,groupName,cityName;

    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_industry_list;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(IndustryViewModel.class);
    }

    @Override
    protected void init() {
        mBinding.setClick(this);
        mMap = new HashMap<>();
        mMap.put("orderByColumn", "desc");
        initActionBar();
        initAdapter();
        initWindow();
        initData();
    }

    private void initAdapter() {
        mBinding.recycler.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .color(getResources().getColor(R.color.color_f5f5f5))
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.recycler);
        mAdapter = new IndustryListAdapter(mList);
        mAdapter.bindToRecyclerView(mBinding.recycler);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                no = mList.get(position).getNo();
                DialogHelper.showProgressDialog(IndustryListActivity.this, "").setCanceledOnTouchOutside(true);
                mViewModel.getState(no);
            }
        });
        mBinding.refreshLayout.setEnableRefresh(true);
        mBinding.refreshLayout.setEnableLoadMore(true);
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mIsLoadMore = true;
                getData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mIsLoadMore = false;
                getData();
            }
        });
        mViewModel.ldType.observe(this, this::addTab);


        mViewModel.ldState.observe(this, state -> {
            switch (state) {//0未上架 1已删除 2正常
                case 0:
                    MToast.showToast(this, "当前数据已下架");
                    DialogHelper.showProgressDialog(this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
                    mIsLoadMore = false;
                    getData();
                    break;
                case 1:
                    MToast.showToast(this, "当前数据已删除");
                    DialogHelper.showProgressDialog(this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
                    mIsLoadMore = false;
                    getData();
                    break;
                case 2:
                    ActivityJump.startActivity(PathMerchant.IndustryDetailActivity, Pair.create(RouterKey.NO, no));
                    break;
            }
        });

    }

    public void addTab(List<IndustryCategoryEntity> list) {
        IndustryCategoryEntity entity = new IndustryCategoryEntity("全部", "");
        list.add(0, entity);

        for (int a = 0; a < list.size(); a++) {
            mBinding.tabIndustryCategory.addTab(mBinding.tabIndustryCategory.newTab().setText(list.get(a).getCategoryName()).setTag(list.get(a).getCategoryNo()));
        }
        mBinding.tabIndustryCategory.addOnTabSelectedListener(new CustomXTabLayout.SimpleSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mMap.put("parkTypeNo", tab.getTag());
                resetChoose();
                mIsLoadMore = false;
                getData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        mBinding.tvLeve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(leveTypeName)){
                    mBinding.tvLeve.updateChooseTextStatus(-2, leveTypeName);
                }else {
                    mBinding.tvLeve.updateChooseTextStatus(-2, mBinding.tvLeve.getKeyName());
                }
                if (mLeveList.size() == 0) {
                    mViewModel.getLevel();
                } else {
                    mLevePop.showPopwindow0(mBinding.popLine);
                }
            }
        });
        mBinding.tvGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(groupName)){
                    mBinding.tvGroup.updateChooseTextStatus(-2, groupName);
                }else {
                    mBinding.tvGroup.updateChooseTextStatus(-2, mBinding.tvGroup.getKeyName());
                }
                if (mGroupList.size() == 0) {
                    mViewModel.getGroup();
                } else {
                    mGroupPop.showPopwindow0(mBinding.llChoose);
                }
            }
        });
        mBinding.tvLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(cityName)){
                    mBinding.tvLocation.updateChooseTextStatus(-2, cityName);
                }else {
                    mBinding.tvLocation.updateChooseTextStatus(-2, mBinding.tvLocation.getKeyName());
                }
                if (cityData == null) {
                    DialogHelper.showProgressDialog(IndustryListActivity.this, null, "", 0, false, null).setCanceledOnTouchOutside(true);
                    mViewModel.getServiceCity();
                } else {
                    mAddressPop.setData(cityData, true);
                    mAddressPop.showPopwindow0(mBinding.llChoose);
                }
            }
        });
    }

    //获取数据
    private void initData() {
        mViewModel.ldData.observe(this, this::syncData);
        mViewModel.liveDataCityList.observe(this, this::showCityPopWindow);
        mViewModel.ldLeve.observe(this, data -> {
            IndustryCategoryEntity entity = new IndustryCategoryEntity("不限", "");
            data.add(0, entity);
            mLeveList.addAll(data);
            mLevePop.showPopwindow0(mBinding.llChoose);
            mLevePop.setData(mLeveList);
        });
        mViewModel.ldGroup.observe(this, data -> {
            IndustryCategoryEntity entity = new IndustryCategoryEntity("不限", "");
            data.add(0, entity);
            mGroupList.addAll(data);
            mGroupPop.showPopwindow0(mBinding.llChoose);
            mGroupPop.setData(mGroupList);
        });
        mViewModel.getType();
        DialogHelper.showProgressDialog(this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        mMap.put("timeSort", true);
        getData();
    }

    private void initWindow() {
        initAdressPop();
        mLevePop = new SelectTypeWindow(this);
        mLevePop.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                isChange1 = true;
                IndustryCategoryEntity mEntity = (IndustryCategoryEntity) key1;
                leveTypeName= mEntity.getCategoryName();
                mBinding.tvLeve.updateChooseTextStatus(1, mEntity.getCategoryName());
                mMap.put("assistantSectionLevelNo", mEntity.getCategoryNo());
                mIsLoadMore = false;
                getData();
            }
        });
        mLevePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (isChange1) {
                    mBinding.tvLeve.updateChooseTextStatus(1, null);
                }else{
                    mBinding.tvLeve.updateChooseTextStatus(0, mBinding.tvLeve.getKeyName());
                }

            }
        });
        mGroupPop = new SelectTypeWindow(this);
        mGroupPop.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                isChange2 = true;
                IndustryCategoryEntity mEntity = (IndustryCategoryEntity) key1;
                groupName=mEntity.getCategoryName();
                mBinding.tvGroup.updateChooseTextStatus(1, mEntity.getCategoryName());
                mMap.put("clusterNo", mEntity.getCategoryNo());
                mIsLoadMore = false;
                getData();
            }
        });
        mGroupPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (isChange2) {
                    mBinding.tvGroup.updateChooseTextStatus(1, null);
                } else {
                    mBinding.tvGroup.updateChooseTextStatus(0, mBinding.tvGroup.getKeyName());
                }

            }
        });
    }

    private void initAdressPop() {
        mAddressPop = new ThreeLevelAreaWindow(this) {
            @Override
            protected void resultContent(String name, String simpleName) {

                if (name.equals("全国")) {
                    cityName="不限";
                    mBinding.tvLocation.updateChooseTextStatus(1,"不限");
                } else {
                    cityName=simpleName;
                    mBinding.tvLocation.updateChooseTextStatus(1,simpleName);

                }
            }
        };
        mAddressPop.setMemberHeight();
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setProvinceSingle();
        mAddressPop.setCitySingle();
        mAddressPop.setAreaSingle();
        mAddressPop.setBgView(mBinding.grayLayoutInvestment);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(com.swgk.core.view.areapopup.GoodsSourceLocationEntity entity) {
                isChange3 = true;
                if (entity.getProvinceNo() == null || entity.getProvinceNo().equals("")) {
                    mMap.remove("provinceCode");
                    mMap.remove("cityCode");
                    mMap.remove("regionCode");
                    mIsLoadMore = false;
                    getData();
                    return;
                }
                mMap.put("provinceCode", entity.getProvinceNo());
                mMap.put("cityCode", entity.getCityNo());
                mMap.put("regionCode", entity.getAreaNo());
                mIsLoadMore = false;
                getData();
            }

        });
        mAddressPop.setOnDismissListener(() -> {
            if (isChange3) {
                mBinding.tvLocation.updateChooseTextStatus(1, null);
            } else {
                mBinding.tvLocation.updateChooseTextStatus(0, mBinding.tvLocation.getKeyName());
            }
        });
    }

    public void showCityPopWindow(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> cityDatas) {
        this.cityData = cityDatas;
        String proName = "不限", cityName = "不限", areaName = "不限";
        mAddressPop.setDataAndPosition(cityDatas, proName, cityName, areaName, true, true);
        mAddressPop.showPopwindow0(mBinding.llChoose);
    }

    private void setPublishState(int state) {
        switch (state) {
            case STATE_PUBLISH_TIME_DOWN://降序
                STATE_PUBLISH_TIME = STATE_PUBLISH_TIME_DOWN;
                mBinding.rlPublishTime.setBackground(getResources().getDrawable(R.drawable.search_new_blue_bg));
                mBinding.imgPublishUp.setImageResource(R.mipmap.icn_up_arrow_n);
                mBinding.imgPublishDown.setImageResource(R.mipmap.icon_down_red);
                mBinding.tvPublishContent.setTextColor(getResources().getColor(R.color.color_EF4033_link));
                break;
            case STATE_PUBLISH_TIME_UP://升序
                STATE_PUBLISH_TIME = STATE_PUBLISH_TIME_UP;
                mBinding.rlPublishTime.setBackground(getResources().getDrawable(R.drawable.search_new_blue_bg));
                mBinding.imgPublishUp.setImageResource(R.mipmap.icon_up_red);
                mBinding.imgPublishDown.setImageResource(R.mipmap.ic_down_arrow_n);
                mBinding.tvPublishContent.setTextColor(getResources().getColor(R.color.color_EF4033_link));
                break;
            case STATE_PUBLISH_TIME_NONE://未选择
                STATE_PUBLISH_TIME = STATE_PUBLISH_TIME_NONE;
                mBinding.rlPublishTime.setBackground(getResources().getDrawable(R.drawable.search_bg));
                mBinding.imgPublishUp.setImageResource(R.mipmap.icn_up_arrow_n);
                mBinding.imgPublishDown.setImageResource(R.mipmap.ic_down_arrow_n);
                mBinding.tvPublishContent.setTextColor(getResources().getColor(R.color.FF333333));
                break;
        }
    }

    private void initActionBar() {
        mBinding.includeActionBar.ivBackRed.setOnClickListener(a -> finish());
        mBinding.includeActionBar.editSearchRed.setHint("请输入产业园区名称");
        mBinding.includeActionBar.editSearchRed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mBinding.includeActionBar.editSearchRed.getText().toString().equals("")) {
                    mBinding.includeActionBar.ivCloseRed.setVisibility(GONE);
                } else {
                    mBinding.includeActionBar.ivCloseRed.setVisibility(VISIBLE);
                }
            }
        });

        mBinding.includeActionBar.ivCloseRed.setOnClickListener(v -> {
            mBinding.includeActionBar.editSearchRed.setText("");
            if (mIsHasSearch) {
                closeKeybord();
                mMap.remove("likeParkName");
                mIsLoadMore = false;
                getData();
            }
        });
        mBinding.includeActionBar.editSearchRed.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mBinding.includeActionBar.editSearchRed.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                closeKeybord();
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    mIsHasSearch = true;
                    if (TextUtils.isEmpty(mBinding.includeActionBar.editSearchRed.getText().toString())) {
                        MToast.showToast(IndustryListActivity.this, "请输入产业园区名称");
                        return true;
                    }
                    DialogHelper.showProgressDialog(IndustryListActivity.this, "搜索中").setCanceledOnTouchOutside(true);
                    //搜索
                    mIsHasSearch = true;
                    closeKeybord();
                    mMap.put("likeParkName", mBinding.includeActionBar.editSearchRed.getText().toString());
                    mIsLoadMore = false;
                    getData();
                }
                return false;
            }
        });
        mBinding.includeActionBar.rightViewRed.setOnClickListener(a -> {
            if (mBinding.includeActionBar.editSearchRed.getText().toString().equals("")) {
                MToast.showToast(this, "请输入产业园区名称");
            }
            //搜索
            mIsHasSearch = true;
            closeKeybord();
            mMap.put("likeParkName", mBinding.includeActionBar.editSearchRed.getText().toString());
            mIsLoadMore = false;
            getData();
        });
    }

    private void getData() {
        mViewModel.getInvestmentData(mIsLoadMore, mMap);

    }

    @Override
    public void onClick(View v) {
      if (v.getId() == R.id.rl_publish_time) {
            if (STATE_PUBLISH_TIME == STATE_PUBLISH_TIME_NONE) {
                setPublishState(STATE_PUBLISH_TIME_UP);
                mMap.put("timeSort", false);
            } else if (STATE_PUBLISH_TIME == STATE_PUBLISH_TIME_UP) {
                setPublishState(STATE_PUBLISH_TIME_DOWN);
                mMap.put("timeSort", true);
            } else {
                setPublishState(STATE_PUBLISH_TIME_UP);
                mMap.put("timeSort", false);
            }
            mIsLoadMore = false;
            getData();
        }
    }

    /**
     * 产业园区办数据
     *
     * @param
     */
    public void syncData(ListResponse<List<IndustryListEntity>> entity) {
        mBinding.refreshLayout.finishRefresh();
        mBinding.refreshLayout.finishLoadMore();
        if (mViewModel.pageNum == 1) {
            mList.clear();
        }
        if (entity.getList() != null) {
            mList.addAll(entity.getList());
        }
        if (mList.size() == 0) {
            mAdapter.setEmptyView(R.layout.merchant_empty_views);
        }

        mAdapter.notifyDataSetChanged();


        //
        if (entity.getCurrentPage() < entity.getTotalPage()) {
            mIsLoadMore = true;
            mBinding.refreshLayout.resetNoMoreData();
        } else {
            mBinding.refreshLayout.finishLoadMoreWithNoMoreData();
        }
    }

    /**
     * 重置筛选
     */
    private void resetChoose() {
        groupName="";
        leveTypeName="";
        cityName="";
        mBinding.tvLocation.updateChooseTextStatus(0,"地区");
        mBinding.tvLeve.updateChooseTextStatus(0,"行政等级");
        mBinding.tvGroup.updateChooseTextStatus(0,"产业集群");
        setPublishState(STATE_PUBLISH_TIME_NONE);
        mMap.remove("provinceCode");
        mMap.remove("cityCode");
        mMap.remove("regionCode");
        mMap.remove("assistantSectionLevelNo");
        mMap.remove("clusterNo");
        mMap.put("timeSort", true);
        initAdressPop();
    }

    @Override
    public boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MainEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_MERCHANT_INDUSTRY_REFRESH) {
            mBinding.refreshLayout.autoRefresh();
        }
    }
}
